package com.ljd.server.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.ljd.server.pojo.Admin;
import com.ljd.server.pojo.Menu;
import com.ljd.server.mapper.MenuMapper;
import com.ljd.server.service.IMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.List;

import static com.baomidou.mybatisplus.core.toolkit.IdWorker.getId;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ljd
 * @since 2022-01-19
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements IMenuService {

    @Autowired
    private MenuMapper menuMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 根据用户id查询菜单列表
     * @return
     */
    @Override
    public List<Menu> getMenusByAdminId() {

        // 获取当前请求的用户的id
        Integer adminId = ((Admin) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getId();

        // 获取redis操作对象
        ValueOperations valueOperations = redisTemplate.opsForValue();
        // 先从redis中获取当前用户的菜单
        List<Menu> menus = (List<Menu>)valueOperations.get("menu" + adminId);

        // 判断list是否为null或者list中的size是否为0
        if (CollectionUtils.isEmpty(menus)) {
            // 从mysql数据库中获取用户菜单列表
            menus = menuMapper.getMenusByAdminId(adminId);
            // 然后存入redis中,方便下次获取时直接从redis中获取,加快速度
            valueOperations.set("menu"+adminId,menus);
        }

        return menus;
    }


    /**
     * 根据角色获取菜单列表
     * @return
     */
    @Override
    public List<Menu> getMenusWithRole() {
        return menuMapper.getMenusWithRole();
    }


    /**
     * 查询所有菜单
     */
    @Override
    public List<Menu> getAllMenus() {
        return menuMapper.getAllMenus();
    }
}
